package com.tabuleiro.negocio.base.impl;

import java.io.Serializable;
import java.util.Map;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Query;
import org.hibernate.Session;

import com.tabuleiro.negocio.base.DefaulService;

public class DefaultServiceImpl<T, K extends Serializable> implements DefaulService<T, K> {

	 @Inject
	 private Session session;

	public <T> T create(T t) {
		session.persist(t);
        session.flush();
        session.refresh(t);
        return t;
	}

	public <T> T update(T t) {
		 session.merge(t);
	     return t;
	}

	public <T, PK extends Serializable> void delete(Class<T> type, PK id) {
		@SuppressWarnings("unchecked")
        T ref = (T) session.get(type, id);
        session.delete(ref);
		
	}

	public <T, PK extends Serializable> T find(Class<T> type, PK id) {
		return (T) session.get(type, id);
	}

	public void refresh(T object) {
		
        session.refresh(object);
		
	}

	public T attach(T object) {
		session.merge(object);
		return object;
	}

	public void discard(T object) {
		session.evict(object);
		
	}

	public Session getSession() {
		return session;
	}

	public T findUniqueWithNamedQuery(String queryNome,	Map<String, Object> parametros) {
		Query query = session.getNamedQuery(queryNome);
		for (String chave : parametros.keySet()) {
			query.setParameter(chave, parametros.get(chave));
		}
		query.setMaxResults(1);
		return (T) query.uniqueResult();
	}
	 
		

}
